package com.beaven.model.data.group;

import com.beaven.model.Factory;
import com.beaven.model.data.DataSource;
import com.beaven.model.data.helper.GroupHelper;
import com.beaven.model.model.api.RspModel;
import com.beaven.model.model.card.GroupCard;
import com.beaven.model.model.db.Group;
import java.util.List;
import rx.Subscriber;
import rx.subscriptions.CompositeSubscription;
import timber.log.Timber;

/**
 * author: Beaven
 * time: 2017/6/2 10:27
 */

public class GroupPresenter implements DataSource.SuccessCallBack<List<Group>> {

  private GroupRepository repository;
  private OnGroupLoad load;
  private CompositeSubscription subscription;

  public GroupPresenter(OnGroupLoad load) {
    this.load = load;
    repository = new GroupRepository();
    subscription = new CompositeSubscription();
  }

  public void loadData() {
    repository.load(this);
    Timber.e("网络请求--获取群组列表");
    subscription.add(
        GroupHelper.getGroupList().subscribe(new Subscriber<RspModel<List<GroupCard>>>() {
          @Override public void onCompleted() {
            Timber.e("网络请求--获取群组列表---结束");
          }

          @Override public void onError(Throwable e) {
            Timber.e(e);
          }

          @Override public void onNext(RspModel<List<GroupCard>> listRspModel) {
            if (listRspModel.isSuccess()) {
              List<GroupCard> cardList = listRspModel.getResult();
              if (cardList == null || cardList.size() == 0) return;
              Factory.getGroupCenter().dispatchGroup(cardList.toArray(new GroupCard[0]));
            } else {
              Factory.decodeRspCode(listRspModel, null);
            }
          }
        }));
  }

  public void loadLocal() {
    repository.load(this);
  }

  public void destroy() {
    subscription.clear();
    repository.dispose();
  }

  @Override public void notifyData() {
    load.notifyGroup();
  }

  @Override public void loadDataSuccess(List<Group> groups) {
    Timber.i("接收数据库变更---群组列表");
    load.loadGroup(groups);
  }

  public interface OnGroupLoad {
    void loadGroup(List<Group> groups);

    void notifyGroup();
  }
}
